import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
import router from 'vue-router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json'
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const { success, msg } = response.data
    if (success || success === undefined) {
      return response.data
    } else {
      Message({
        type: 'error',
        message: msg
      })
      return Promise.reject(new Error(msg))
    }
  },
  error => {
    if (error.response.status === 401) {
      Message({
        type: 'error',
        message: '登录状态过期，请重新登陆'
      })
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message({
        type: 'error',
        message: error.response.data
      })
    }
    return Promise.reject(error)
  }
)

export default service
